package com.demo.service;

import com.demo.entity.User;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description:  动态代理
 *   a. 实现InvocationHandler的invoke方法
 *   b. 用Proxy.newProxyInstance方法拿到代理类
 *
 *   优点：可以代理所有方法
 *   还是需要被代理类实现接口
 * @author: ayouman
 * @date: 2024/6/26 23:20
 */
public class UserServiceJDKProxy implements InvocationHandler {
    private IUserService userService;
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("执行方法之前");
        Object res = method.invoke(userService, args);
        System.out.println("执行方法之后");
        return res;
    }

    public IUserService getProxy(IUserService proxyObject)
    {
        this.userService = proxyObject;
        return (IUserService) Proxy.newProxyInstance(proxyObject.getClass().getClassLoader(), proxyObject.getClass().getInterfaces(), this);
    }
}
